<?php

declare(strict_types=1);

namespace app\api\controller;

use think\facade\Request;
use think\facade\Db;
use app\api\controller\WxpayService;
use app\api\controller\Withdrawal;



class Order
{

    /**
     * 生成订单
     */
    public function create()
    {
        $openid = Request::header('openid');
        $total = Request::param('total');
        $uid = Db::name('user')->where('wechat_openid', $openid)->find()['uid'];
        // 生成订单信息
        $data = [
            'uid' => $uid,
            'total' => $total,
            'order_sn' => get_sn(),
            'create_time' => time(),
            'update_time' => time(),
            'pay_status' => 0,
        ];
        Db::name('order')->insert($data);
        $order = Db::name('order')->where('order_sn', $data['order_sn'])->find();
        // var_dump($order);


        // 统一下单信息
        $mchid = '商户号';          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
        $appid = '公众号appid';  //微信支付申请对应的公众号的APPID
        $appKey = '公众号密钥';   //微信支付申请对应的公众号的APP Key
        $apiKey = '商户支付API密钥';   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
        $wxPay = new WxpayService($mchid, $appid, $appKey, $apiKey, $openid);

        // 统一下单
        $outTradeNo = $data['order_sn'];     //商品订单号
        $totalFee = $order['total'];          //付款金额，单位:元
        $orderName = '微信零钱';    //订单标题
        $notifyUrl = 'https://api.lq.galaxy-x.cn/api/Order/notify';     //付款成功后的回调地址(不要有问号)
        $timestamp = time();      //付款时间
        $jsApiParameters = $wxPay->createJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp);
        // $jsApiParameters = json_decode($jsApiParameters);
        // var_dump($jsApiParameters);
        return jsonData(1, '订单创建成功', $jsApiParameters);
    }

    /**
     * 用户订单列表
     */
    public function list()
    {
        $openid = Request::header('openid');
        $page = Request::param('page');
        $page_size = Request::param('page_size');
        $uid = Db::name('user')->where('wechat_openid', $openid)->find()['uid'];
        $list = Db::name('order')->where(array('uid' => $uid, 'pay_status' => 1))->order('update_time', 'desc');
        $total = $list->select()->count();
        $order = $list->page((int)$page, (int)$page_size)->select()->each(function ($item, $key) {
            $item['type'] = 1;
            return $item;
        });
        // $order = $list->page((int)$page, (int)$page_size)->select();
        $data = [
            'data' => $order,
            'total' => $total
        ];
        // var_dump($list);
        // die;
        return jsonData(1, '查询成功', $data);
    }

    /**
     * 更新用户总支付订单信息
     */
    public function updateUserOrder($result)
    {
        // $uid = Request::param('uid');
        // 微信支付订单回调会调用多次，所以查询该用户已支付的订单，来累计订单额，更新到用户表
        $uid = Db::name('order')->where('order_sn', $result['out_trade_no'])->find()['uid'];
        $orders = Db::name('order')->where(array('uid' => $uid, 'pay_status' => 1))->select()->toArray();
        $total_amount = 0;
        for ($row = 0; $row < count($orders); $row++) {
            $total_amount = $total_amount + $orders[$row]['total'];
        };
        $data['pay_money'] = $total_amount;
        $data['pay_order'] = count($orders);
        // 更新用户总支付金额及订单数
        Db::name('user')->where('uid', $uid)->update($data);
    }

    /**
     * 微信支付回调
     */
    public function notify()
    {
        Db::startTrans();
        try {
            $testxml = file_get_contents("php://input");
            $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
            $result = json_decode($jsonxml, true);
            if (is_array($result)) {
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                    // $order = Db::name('order')->where(array('order_sn' => $result['out_trade_no'], 'pay_status' => 0))->find();
                    $pay_data['pay_status'] = 1;
                    $pay_data['update_time'] = time();
                    Db::name('order')->where(array('order_sn' => $result['out_trade_no'], 'pay_status' => 0))->update($pay_data);
                    // 更新用户已支付的订单额
                    $this->updateUserOrder($result);
                    // 创建提现订单
                    $withdrawal = new Withdrawal();
                    $withdrawal->create($result);
                    // 发起提现
                    // $withdrawal -> userpay($wid);

                }
            }
            // 提交事务
            Db::commit();
            echo 'SUCCESS';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }
}
